import Vue from 'vue'
import Router from 'vue-router'
import Hello from "@/components/Hello";
import Login from '@/components/Login'
import Home from "@/components/Home";
import Welcome from "../components/Welcome";
import UserInfo from "../components/user/UserInfo";
import Room from "../components/zy/Room";
import Community from "@/components/zy/Community";
import Building from "@/components/zy/Building";
import Unit from "@/components/zy/Unit";

Vue.use(Router)

const router = new Router({
    routes: [
        {path: '/', redirect: '/hello'},
        {path: '/hello', component: Hello},
        {path: '/login', component: Login},
        // 防止/home主体内容为空 设置redirect: '/welcome' 自动用Welcome补充内容
        {
            path: '/home', component: Home, redirect: '/welcome',
            children: [
                {path: '/welcome', component: Welcome},
                {path: '/userInfo', component: UserInfo},
                {path: '/room', component: Room},
                {path: '/community', component: Community},
                {path: '/building', component: Building},
                {path: '/unit', component: Unit},
            ]
        }
  ]
})

//挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作---类似拦截器
router.beforeEach((to, from, next) => {
    // 规则1：如果目标是登录页，直接放行
    if (to.path === '/login' || to.path === '/hello')
        return next();

    // 检查门票（从sessionStorage读取token）
    const tokenStr = window.sessionStorage.getItem('token');

    // 规则2：没门票 且 不是去公开页面(/hello) → 踢回登录页
    if (!tokenStr) {
        return next('/login');
    }
    // 其他情况：有门票或去公开页面 → 放行
    next();
})
export default router
